import { config, loadRemote } from '@vimi/utils-tool'

const pdfCdn = {
  baseUrl: '/libs/pdf.js/2.7.570',
  js: '/pdf.min.js',
  worker: '/pdf.worker.min.js',
}

let loading = false
const loadQueue = []

export const loadPdf = () => {
  if (loading) {
    return new Promise((resolve, reject) => {
      loadQueue.push({ resolve, reject })
    })
  }
  loading = true

  const gBaseUrl = config.baseUrl
  const { baseUrl, js, worker } = pdfCdn
  return loadRemote(`${gBaseUrl}${baseUrl}${js}`, 'pdfjsLib')
    .then(() => {
      window.pdfjsLib.GlobalWorkerOptions.workerSrc = `${gBaseUrl}${baseUrl}${worker}`
      loadQueue.forEach(it => it.resolve(window.pdfjsLib))
      return window.pdfjsLib
    })
    .catch(err => {
      loadQueue.forEach(it => it.reject(err))
      throw new Error(err)
    })
    .finally(() => {
      loading = false
      loadQueue.length = 0
    })
}

/**
 * 显示pdf
 * @param {HTMLElement} container DOM
 * @param {string} pageUrl paf path
 * @param {Object} param2 options
 * @returns Promise
 */
export const renderPdf = async (container, pageUrl, { width = 792 } = {}) => {
  const pdfjsLib = await loadPdf()
  const loadingTask = pdfjsLib.getDocument(pageUrl)
  return loadingTask.promise.then(pdfDocument => {
    container.innerHTML = ''
    const promises = []
    for (let page = 1; page <= pdfDocument.numPages; page++) {
      const canvas = document.createElement('canvas')
      container.appendChild(canvas)
      promises.push(
        pdfDocument.getPage(page).then(pdfPage => {
          const viewport = pdfPage.getViewport({
            scale: width / pdfPage.getViewport({ scale: 1.0 }).width,
          })
          canvas.width = viewport.width
          canvas.height = viewport.height
          return pdfPage.render({
            canvasContext: canvas.getContext('2d'),
            viewport,
          })
        })
      )
    }
    return Promise.all(promises)
  })
}
